package org.finesys.tika.config;

import lombok.RequiredArgsConstructor;
import org.apache.tika.Tika;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.Parser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;

@Configuration
@RequiredArgsConstructor
public class ApplicationTikaConfig {

    private final ResourceLoader resourceLoader;

    @Bean
    public Tika tika() throws IOException, TikaException, SAXException {
        Resource resource = resourceLoader.getResource("classpath:tika-config.xml");
        InputStream inputStream = null;
        if (resource.exists()) {
            inputStream = resource.getInputStream();
        } else {
            inputStream = resourceLoader.getClassLoader().getResourceAsStream("/tika-config.xml");
        }
        if (inputStream == null) {
            throw new RuntimeException("tika-config.xml not found");
        }
        TikaConfig config = new TikaConfig(inputStream);
        //校验器
        Detector detector = config.getDetector();
        //解析器
        Parser autoDetectParser = new AutoDetectParser(config);
        return new Tika(detector, autoDetectParser);
    }
}
